/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow
 * @lint-ignore-every XPLATJSCOPYRIGHT1
 */

import * as React from "react";
import { DeviceEventEmitter, View, Platform, StatusBar } from "react-native";
import { createAppContainer } from "react-navigation";
import { Provider, observer, inject } from "mobx-react";
import SplashScreen from "react-native-splash-screen";
import TabBar from "./code/View/TabBar";
import NavigationService from "./code/Service/NavigationService";
import store from "./code/Model";
import { NoticeKeys } from "./code/Utils/utils";
import Login from "./code/Login";
import UserStore from "./code/Model/UserStore";
const AppContainer = createAppContainer(TabBar);

interface Props extends React.Props<any> {
  userStore: UserStore;
}
interface State {
  isLogin: boolean;
  isLoading: boolean; // 是否显示加载页
}
@inject("userStore")
@observer
class App extends React.Component<Props, State> {
  _subscription: any;

  constructor(props: Props) {
    super(props);
    this.state = {
      isLogin: this.props.userStore.isLogin,
      isLoading: true
    };
  }

  render() {
    let routePage = this.state.isLogin ? (
      <View style={{ flexDirection: "column", flex: 1 }}>
        <StatusBar
          backgroundColor={"tomato"}
          animated
          translucent={false}
          networkActivityIndicatorVisible
          barStyle={"light-content"}
        />
        <AppContainer
          ref={(ref: any) => {
            NavigationService.setTopLevelNavigator(ref);
          }}
        />
      </View>
    ) : (
      <View style={{ flexDirection: "column", flex: 1 }}>
        <StatusBar
          backgroundColor={"tomato"}
          animated
          translucent
          networkActivityIndicatorVisible
          barStyle={"light-content"}
          hidden
          showHideTransition="fade"
        />
        <Login userStore={this.props.userStore} />
      </View>
    );
    return this.state.isLoading ? (
      <View style={{ backgroundColor: "transparent", flex: 1 }} />
    ) : (
      routePage
    );
  }

  componentDidMount() {
    this._subscription = DeviceEventEmitter.addListener(
      NoticeKeys.Notice_Key_Login_State,
      () => {
        this.setState({
          isLogin: this.props.userStore.isLogin
        });
      }
    );
    // 解决异步读取登录状态的问题
    setTimeout(
      () => {
        this.setState({
          isLogin: this.props.userStore.isLogin,
          isLoading: false
        });
      },
      Platform.OS === "ios" ? 0.001 : 30
    );
    SplashScreen.hide();
  }

  componentWillUnmount() {
    this._subscription.remove();
  }
}

export default function setup(): any {
  class Root extends React.Component {
    render() {
      return (
        <Provider {...store}>
          <App userStore={store.userStore} />
        </Provider>
      );
    }
  }
  return Root;
}
